const { Goods } = require("../models.js");
const Router = require('koa-router');
const { Op } = require('sequelize');
const { getvalue } = require('../../core/getsearch.js');
let router = new Router({
    prefix:'/goods'
})

//搜索
router.post('/search',async(ctx)=>{
    let keyword = ctx.request.body.key;
	let sortkey = Object.keys(ctx.request.body)[2];
	let { sortvalue,sqlsort } = getvalue(sortkey,ctx.request.body)
	let page = ctx.request.body.page;//当前页数
	let num = 10  //每页显示数量
	let start = (page-1)*num  //开始位置
    try {
        await Goods.findAll({
            where:{
                NAME:{
                    [Op.like]:'%'+ keyword +'%'
                }
            },
			order:[
				[sqlsort,sortvalue]
			],
			offset:start,
			limit:num
        }).then(res=>{
            ctx.body = {
                code:200,
                msg:res
            }
        })
    } catch (error) {
        ctx.body = {
            code:400,
            msg:error
        }
    }
})


/* 获取商品详情信息的接口 */
router.post('/GoodsInfo',async(ctx)=>{
    try {
        let data = ctx.request.body.goodsId;
        await Goods.findAll({
            where:{ PID:data }
        }).then(res=>{
            ctx.body = {
                code:200,
                msg:res
            }
        })
    } catch (error) {
        ctx.body = {
            code:400,
            msg:"数据获取失败"
        }
    }
})



module.exports = router;